<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px">
      <el-form-item label="项目名称:">
        <span style="font-weight: bold;">{{ query.projectName }}</span>
      </el-form-item>
      <el-form-item label="项目ID:">
        <span style="font-weight: bold;">{{ query.projectId }}</span>
      </el-form-item>
      <el-form-item>
        <el-button plain type="primary" @click="updateForm('create')"
          v-hasPermi="['system:project:group:member:create']" v-if="permission && permission.allowAddMember">
          <Icon class="mr-5px" icon="ep:plus" />
          新增成员
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true">
      <el-table-column align="center" label="用户昵称" prop="memberName" />
      <el-table-column align="center" label="加入时间" prop="createTime" />
      <el-table-column align="center" label="项目角色" prop="projectRole">
        <template #default="scope">
          <div v-if="!isEditing(scope.row.id)">
            {{ getRoleName(scope.row.projectRoleId) }}
          </div>
          <div v-else>
            <el-select v-model="scope.row.projectRoleId" @change="finishEdit(scope.row)">
              <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"
                :disabled="item.disabled && query.defaulted == '1'" />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column :width="300" align="center" label="管理"
        v-if="permission.allowDeleteMember || permission.allowUpdateMember">
        <!-- 当前用户的默认项目成员 不显示编辑和删除 -->
        <template #default="scope">
          <el-button link @click="startEdit(scope.row.id)" type="primary"
            v-if="!(userName == scope.row.memberName && scope.row.projectRoleId == 'admin' && query.defaulted == '1')">
            编辑 </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-if="!(userName == scope.row.memberName && scope.row.projectRoleId == 'admin' && query.defaulted == '1') && permission.allowDeleteMember"
            v-hasPermi="['system:project:group:member:delete']"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表单弹窗：添加/修改 -->
    <MemberForm ref="formRef" @success="getList" />
  </ContentWrap>
</template>
<script lang="ts" setup>
defineOptions({ name: 'Store' })
import * as ProjectApi from '@/api/project'
import MemberForm from './MemberForm.vue'
import { useUserStore } from '@/store/modules/user'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const userStore = useUserStore()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { currentRoute } = useRouter() // 路由对象
const { query } = unref(currentRoute)
const loading = ref(false) // 列表的加载中
const list = ref([] as any) // 列表的数据
const permission = ref({} as any)
const queryParams = reactive({
  projectId: query.projectId
})
const queryFormRef = ref() // 搜索的表单
const userName = computed(() => userStore.user.nickname ?? '')
const editingId = ref('');
const roleList = ref([] as any)

const isEditing = (id) => {
  return id == editingId.value;
}

const startEdit = (id) => {
  editingId.value = id;
}
const getRoleName = (id) => {
  return roleList.value.find(r => r.value == id).label
}
const finishEdit = (row) => {
  editingId.value = '';
  const params = {
    id: row.id,
    projectId: row.projectId,
    projectRoleId: row.projectRoleId,
    memberId: row.memberId,
    inviterId: row.inviterId
  }
  ProjectApi.updateMemberRole(params).then(res => {
    if (res) {
      message.success(t('common.updateSuccess'))
    }
  }).catch(error => {
    console.log(error)
  }).finally(() => {
    getList()
    getPermission()
  })

}
// 获取项目角色
const getProjectRoleList = async () => {
  loading.value = true
  try {
    const data = getIntDictOptions(DICT_TYPE.PROJECT_ROLE)
    data.forEach(item => {
      if (item.value == 'admin') {
        item.disabled = true
      }
    })
    roleList.value = JSON.parse(JSON.stringify(data))
  } finally {
    loading.value = false
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProjectApi.getProjectMemberList(queryParams)
    list.value = data
  } finally {
    loading.value = false
  }
}

// 获取成员权限
const getPermission = async () => {
  loading.value = true
  try {
    const data = await ProjectApi.getProjectMemberPermission(queryParams)
    permission.value = data
  } finally {
    loading.value = false
  }
}

/** 添加修改操作 */
const formRef = ref()
const updateForm = (type: string, row?: object) => {
  formRef.value.open(type, row)
}

// 删除
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProjectApi.deleteProjectMember({ id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}


/** 初始化 **/
onMounted(() => {
  getList()
  getPermission()
  getProjectRoleList()
})
</script>
<style scoped lang="scss"></style>
